package com.baizhi.cmfz.config;


//import com.baizhi.cmfz.realm.AuthenRealm;
//import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
//import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
import com.baizhi.cmfz.realm.AuthenRealm;
import com.baizhi.cmfz.realm.AuthorRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        Map map = new HashMap();

        // 设置过滤器的规则
        // 配置拦截规则 哪些页面拦截 哪些不拦截 过滤器链 Map map = new HashMap();
        //  修改之前的认证方法
/*** anon 代表匿名可访问 就是不用登录就可以访问 **
 *   authc 代表登录后才能访问 **
 *   支持通配符* **
 *   注意拦截规则 一个一个配置 */
        map.put("/login.jsp", "anon");
        map.put("/login/*", "anon");
        map.put("/main.jsp", "authc");
        map.put("/guru/*", "authc");
        map.put("/menu/*", "authc");
        map.put("/jsp/*", "authc");
        map.put("/article/*", "authc");
        map.put("/banner/*", "authc");
        map.put("/log/*", "authc");
        map.put("/consumer/*", "authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //设置一个安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        return shiroFilterFactoryBean;
    }

    /**
     * 创建一个安全管理器
     * @param authorRealm
     * @Bean 方法的形参 如果对应的类型的对象在工厂中有  会自动装配上
     * @return
     */
    @Bean
    public SecurityManager getSecurityManger(AuthorRealm authorRealm) {

        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        //设置realm
        defaultSecurityManager.setRealm(authorRealm);
        return defaultSecurityManager;
    }

    /**
     * 创建Realm
     * @return
     */
    @Bean
    public AuthorRealm getRealm(){

        return  new AuthorRealm();

    }


    /*** 开启shiro aop注解支持 *
     *  使用代理方式;所以需要开启代码支持;
     *  否则@RequiresRoles等注解无法生效 *
     *  @param securityManager
     *  @return */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
    return authorizationAttributeSourceAdvisor; }
}
